<template>
  <div>
    <el-card class="card">
      <el-scrollbar height="700px">
        <el-table
            :data="documents"
            style="width: 100%"
            border
            stripe
            empty-text="暂无文档数据"
        >
          <el-table-column prop="name" label="文件名" width="250" />
          <el-table-column prop="size" label="文件大小（字节）" width="150" />
          <el-table-column prop="uploadTime" label="上传时间" width="200" />
          <el-table-column prop="type" label="文件类型" width="100" />
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewDocument(row)">查看</el-button>
              <el-button type="danger" size="small" @click="deleteDocument(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <div class="total-info">
        共 {{ total }} 个文档
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios";

// 文档数据
const documents = ref([]);
const total = ref(0);

const fetchDocuments = async () => {
  try {
    const { data } = await axios.get('/api/documents')
    console.log('文档数据: ',data)
    documents.value = data.documents;
    total.value = data.total;
  } catch (e) {
    await Promise.reject(e)
  }
};

// 查看文档
const viewDocument = async (row) => {
  ElMessage.info(`查看文档: ${row.name}`);
  try {
    // 使用 axios 下载文件，设置 responseType 为 'blob'
    const response = await axios.get(`/api/documents/download/${row.name}`, {
      responseType: 'blob'  // 告诉 axios 返回 Blob 对象
    });

    // response.data 是一个 Blob 对象
    const blob = response.data;
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = row.name; // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success(`正在下载: ${row.name}`);
  } catch (error) {
    ElMessage.error(`下载失败: ${row.name}`);
    console.error(error);
  }
};

// 删除文档
const deleteDocument = async(row) => {
  try {
    const { data } = await axios.delete(`/api/documents/${row.name}`)
    console.log('删除文档信息：',data)
    await fetchDocuments()
    ElMessage({
      message: data.message,
      type: 'warning',
    });
  } catch (e) {
    await Promise.reject(e)
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchDocuments();
});
</script>

<style scoped>
.card {
  padding-top: 2%;
  width: 100%;
  height: 100%;
}

.total-info {
  margin-top: 10px;
  text-align: right;
  font-size: 14px;
  color: #606266;
}
</style>